﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Win32;

namespace CrmContrib.Workflow.Activities
{
    public static class FileRegistry
    {
        private static Dictionary<string, FileRegistryEntry> m_Entries = new Dictionary<string, FileRegistryEntry>();

        private static string GenerateFileName(Guid fileID)
        {
            using (var registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\CrmContrib"))
            {
                var defaultBaseFolder = Path.Combine(Path.GetTempPath(), "CrmContribFileRegistry");
                var baseFolder = registryKey.GetValue("FileRegistryBasePath", defaultBaseFolder) as string;
                if (!Directory.Exists(baseFolder)) Directory.CreateDirectory(baseFolder);

                var fileName = Path.Combine(baseFolder, fileID.ToString());
                return fileName;
            }
        }

        public static FileRegistryEntry AddFile(byte[] data)
        {
            var fileID = Guid.NewGuid();
            var fileName = FileRegistry.GenerateFileName(fileID);

            var entry = new FileRegistryEntry()
            {
                FileID = fileID,
                FileName = fileName
            };

            FileRegistry.m_Entries.Add(fileID.ToString(), entry);
            File.WriteAllBytes(entry.FileName, data);

            return entry;
        }

        public static void RemoveFile(string fileID)
        {
            var entry = FileRegistry.GetFile(fileID);
            FileRegistry.m_Entries.Remove(fileID);
            File.Delete(entry.FileName);
        }

        public static FileRegistryEntry GetFile(string fileID)
        {
            return FileRegistry.m_Entries[fileID];
        }
    }
}
